package org.yufan.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.ObjectUtils;
import org.yufan.common.exception.CustomerException;
import org.yufan.common.result.ResultEnum;
import org.yufan.user.bean.User;

import java.util.Date;
import java.util.Map;

/**
 * Created by zxd on 2019/8/4
 **/
@ConfigurationProperties("jwt.config")
@Slf4j
public class JwtUtil {

    private String key;
    private long ttl;

    /**
     * 创建Jwt签名信息
     *
     * @param id
     * @param subject
     * @param roles
     * @return
     */
    public String createJWT(String id, String subject, Map<String,Object> claim) {

        //系统时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder =
                Jwts.builder().setId(id).
                        setSubject(subject).
                        setIssuedAt(now).//签发时间
                        signWith(SignatureAlgorithm.HS256, key);//设置签名秘钥
        builder.setClaims(claim);
        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl));//设置过期时间
        }
        return builder.compact();
    }

    /**
     * 解析jwt签名信息
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr) {
        return Jwts.parser().
                        setSigningKey(key).
                        parseClaimsJws(jwtStr)
                        .getBody();
    }


    /**
     * 将jwt令牌解析为用户信息
     * @param token
     * @return
     * @throws CustomerException
     */
    public User parseUser(String token) throws CustomerException {
        Claims claims = parseJWT(token);
        if (ObjectUtils.isEmpty(claims)) {
            log.error("无效登录凭证!");
            throw new CustomerException(ResultEnum.LOGIN_EXPIRY);
        }
        User user = new User();
        user.setId(claims.get("id", Long.class));
        user.setUsername(claims.get("username", String.class));
        user.setPhone(claims.get("phone", String.class));
        user.setEmail(claims.get("email", String.class));
        user.setCreated(claims.get("created", Date.class));
        user.setUpdated(claims.get("updated", Date.class));
        return user;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }
}
